package com.li.client.management;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.li.client.util.AppStyle;
import com.smartgwt.client.types.Encoding;
import com.smartgwt.client.types.FormMethod;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.HiddenItem;
import com.smartgwt.client.widgets.form.fields.UploadItem;
import com.smartgwt.client.widgets.layout.VLayout;

public class BatchUpLoadManager extends VLayout {
	private DynamicCallbackForm form;
	private ButtonItem btnSave;
	private UploadItem fileItem;
	
	public BatchUpLoadManager() {
		init();
	}
	
	private void init() {
		
		Element element = Document.get().getElementById("uploadIframe");
		if (null != element)
		{
			element.removeFromParent();
		}
		
		form = new DynamicCallbackForm("uploadIframe");
		form.setEncoding(Encoding.MULTIPART);
		form.setMethod(FormMethod.POST);
		form.setCanSubmit(true);
		
		
		fileItem = new UploadItem("upload");
		
		final HiddenItem callbackItem = new HiddenItem("callbackName");
		callbackItem.setName("callbackName");
		
		btnSave = new ButtonItem("Attachment");
		btnSave.setWidth(AppStyle.px120);
		btnSave.setLeft(AppStyle.px20);
		
		btnSave.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() {
			
			@Override
			public void onClick(com.smartgwt.client.widgets.form.fields.events.ClickEvent event)
			{
				String displayValue = fileItem.getDisplayValue();
				int pos = displayValue.lastIndexOf("/");
				String fileName = pos == -1? displayValue : displayValue.substring(pos);
				form.setAction(GWT.getModuleBaseURL() + "dataService?icgDataServiceType=" + "fileUpload&fileName=" + fileName);
				
				form.submitForm();
			}
		});
		
		form.setItems(fileItem, callbackItem, btnSave);
		form.setWidth("98%");
		form.setHeight("20%");
	
		
		form.addFormHandler(new DynamicFormHandler()
		{
			public void onSubmitComplete(DynamicFormSubmitCompleteEvent event)
			{
					String result = event.getResults();
					// Window.alert(result);
					if (result != null && result.trim().length() > 0)
					{
						int begin = result.indexOf("[BEGIN]") + "[BEGIN]".length();
						int end = result.indexOf("[END]");
						result = result.substring(begin, end);
						if (Boolean.valueOf(result.trim())) {
							SC.say("File Uploaded!");
						} else {
							SC.say("File Uploaded failed!");							
						}
					} else {
						SC.say("File Uploaded failed!");
					}

			}
		});
		setMembers(form);
		
	}
	
}
